//
//  LoadingViewController.m
//  NewsReader
//
//  Created by blacksun on 11-2-19.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoadingViewController.h"
#import "NewsReaderAppDelegate.h"
#import "RootViewController.h"


@implementation LoadingViewController

@synthesize sectionContainer;
@synthesize colorArray;
@synthesize activeView;
@synthesize activeHttp;
@synthesize operationQueue;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	
	appDelegate = [UIApplication sharedApplication].delegate;
	UIColor *color1 = [[UIColor alloc] initWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
	UIColor *color2 = [[UIColor alloc] initWithRed:0/255.0 green:0/255.0 blue:51/255.0 alpha:1.0];
	//UIColor *color3 = [[UIColor alloc] initWithRed:0/255.0 green:0/255.0 blue:204/255.0 alpha:1.0];
	NSArray *array = [[NSArray alloc] initWithObjects:color1,color2,nil];
	self.colorArray = array;
	[array release];
	[color1 release];
	[color2 release];
	//[color3 release];
	
	NSOperationQueue *queue = [[NSOperationQueue alloc] init];
	self.operationQueue = queue;
	[queue release];
	
	
}

-(void)viewWillAppear:(BOOL)animated{
	int rand = abs((int)arc4random()%2);

	self.view.backgroundColor = [self.colorArray objectAtIndex:rand];
	

}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	finishLayout = NO;
	finishRequest = NO;
	appDelegate.networkState = NO;

	//从缓存文件中获取用户信息，用户对象里包含了他订阅的类别。
	NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[appDelegate dataFilePath:kUserFile]];
	NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
	appDelegate.user = [unArchiver decodeObjectForKey:kUserDefaultKey];
	[unArchiver release];
	[data release];
	
	
	
	[self buildChildren];
	
	[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeOut) userInfo:nil repeats:NO];
	
	NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(isNetWorkable) object:nil];
	[self.operationQueue addOperation:operation];
	[operation release];
	
	//在一秒后发出更新section或者匿名注册请求，因为1秒后判断网络是否可用的代码已经执行完成
	[self performSelector:@selector(startRequest) withObject:nil afterDelay:1.5];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	//appDelegate = nil;
}


- (void)dealloc {
	self.sectionContainer = nil;
	self.colorArray = nil;
	self.activeView = nil;
	[self.activeHttp stopHttpConnection];
	self.activeHttp = nil;
    [super dealloc];
}

int abs(int number){
    if(number <0)
		return ~(number-1);
    else
		return number;
}

-(void)isNetWorkable{
	appDelegate.networkState = [HttpUtil isNetworkUseable];
}

-(void) startRequest{
	//BOOL isNetworkUseable = [HttpUtil isNetworkUseable];
	if (appDelegate.networkState) {//网络可用
		//NSLog(@"userid=%@",appDelegate.user.userId);
		if ([appDelegate.user.userId length] == 0 || [appDelegate.user.userId isEqualToString:kUser_defaultUserId]) {//如果缓存中没有则从服务器获取并保存倒本地文件缓存
			
			User *newUser = [[User alloc] init];
			appDelegate.user = newUser;
			[newUser release];
			
			NSURL *url = [[NSURL alloc] initWithString:[URLAddress anonymousRegister:appDelegate.user.deviceId]];
			NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
			HttpUtil *httpUtil = [[HttpUtil alloc] init];
			[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishGetUserIdRequest:) isBackGround:NO];
			self.activeHttp = httpUtil;
			[httpUtil release];
			[url release];
			[request release];
			
		}else {
			NSMutableArray *ids = [[NSMutableArray alloc] init];
			for (Section *selected in appDelegate.user.mySections) {
				[ids addObject:[NSString stringWithFormat:@"%@", selected.sectionId]];
			}
			NSString *idStrs = [[NSString alloc] initWithFormat:@"%@",[ids componentsJoinedByString:@","]];
			
			NSString *urlStr = [URLAddress getMySections:idStrs forMe:appDelegate.user.userId];
			NSURL *url = [[NSURL alloc] initWithString:urlStr];
			NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
			HttpUtil *httpUtil = [[HttpUtil alloc] init];
			[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(updateSections:) isBackGround:NO];
			self.activeHttp = httpUtil;
			[httpUtil release];
			[request release];
			[url release];
			
			[idStrs release];
			[ids release];
			
		}
	}else {
		if ([appDelegate.user.userId length] == 0) {//如果缓存中没有则从服务器获取并保存倒本地文件缓存
			User *newUser = [[User alloc] init];
			[appDelegate archiverUser:newUser];//缓存用户对象
			appDelegate.user = newUser;
			[newUser release];
		}
		finishRequest = YES;
	}
}


-(void) buildChildren{
	
	NSString *path = [[NSBundle mainBundle] pathForResource:kDefaultSectionConfig ofType:@"txt"];
	NSArray *defaultSections = [[NSArray alloc] initWithContentsOfFile:path];
	
	NSArray *mySections = appDelegate.user.mySections;
	//NSLog(@"%d",[mySections count]);
	NSMutableArray *lasts = [[NSMutableArray alloc] init];
	while ([lasts count]<kLoadingSectionSize) {
		int rand = abs((int)arc4random()%kLoadingSectionSize);
		NSNumber *number = [[NSNumber alloc] initWithInt:rand];
		if (![lasts containsObject:number]) {//如果得到的随机数没有出现过，则运行
			
			LoadingSectionViewController *childController = [[LoadingSectionViewController alloc] initWithNibName:@"LoadingSectionViewController" bundle:nil];
			
			float width = childController.view.frame.size.width;
			float height = childController.view.frame.size.height;
			childController.view.frame = CGRectMake((rand%3)*width,(rand/3+rand%1)*height,width,height);
			
			NSDictionary *loadSection = [defaultSections objectAtIndex:[lasts count]];
			
			
			UIImageView *imageView = (UIImageView *)[childController.view viewWithTag:100];
			
			
			NSString *imagePath = nil;

			for (int i=0; i<[mySections count]; i++) {
				Section *temp = [mySections objectAtIndex:i];
                
                //NSLog(@"loadid=%@,myid=%@",[loadSection objectForKey:@"sectionId"],temp.sectionId);
				if ([temp.sectionId isEqualToString:[loadSection objectForKey:@"sectionId"]]) {
					imagePath = [temp.oldImageUrl retain];
					break;
				}
			}
            NSString *filePath = [ImageStorgeUtil getFullPathWithImagePath:imagePath];

			UIImage *oldImage = [[UIImage alloc] initWithContentsOfFile:filePath];
			[imagePath release];
			
			if (oldImage) {
				 imageView.image = oldImage;
			 }else {
				 UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[loadSection objectForKey:@"originalImage"] ofType:@"jpg"]];//[UIImage imageNamed:[loadSection objectForKey:@"originalImage"]];
				 imageView.image = image;
				 [image release];
			}
			[oldImage release];
			
			
			
			UILabel *label = (UILabel *)[childController.view viewWithTag:101];
			label.text = [loadSection objectForKey:@"sectionName"];
			
			[self.sectionContainer addSubview:childController.view];
			
			[UIView beginAnimations:nil context:nil];
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			[UIView setAnimationDuration:0.2];
			[UIView setAnimationDelay:2+0.2*[lasts count]];
			if ([lasts count]==kLoadingSectionSize-1) {
				[UIView setAnimationDelegate:self];
				[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
			}
			childController.view.alpha = 1.0;
			[UIView commitAnimations];
			
			[childController release];
			[lasts addObject:number];
		}
		[number release];
	}
	[lasts release];
	[defaultSections release];
}

-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
	finishLayout = YES;
	if (!finishRequest) {
		[self.activeView startAnimating];
	}
	[self gotoMainPage];
}

-(void)timeOut{
	[self.operationQueue cancelAllOperations];
}


- (void)finishGetUserIdRequest:(NSData *)theResponse{
	NSString *responseStr = [[NSString alloc] initWithData:theResponse encoding:NSUTF8StringEncoding];
	NSDictionary * responseDict = [responseStr JSONValue];
	NSString *userId = [NSString  stringWithFormat:@"%@",[responseDict objectForKey:kUserId]];
	appDelegate.user.userId = userId;
	NSArray *sectionsArray = [responseDict objectForKey:kDefaultSections];
	appDelegate.user.mySections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	[appDelegate archiverUser:appDelegate.user];
	[responseStr release];
	[theResponse release];
	finishRequest = YES;
	
	[self gotoMainPage];
}
-(void)updateSections:(NSData *)response{

	appDelegate.user.needUpdateSections = NO;
	NSMutableArray *newSections = nil;
	NSString *responseStr = nil;
	if (response) {
		responseStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        NSLog(@"%@",responseStr);
		NSDictionary * responseDict = [responseStr JSONValue];
		NSArray *sectionsArray = [responseDict objectForKey:@"sections"];
		newSections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
		
	}else {
		newSections = [NSMutableArray array];
	}
	for (int i=0; i<[appDelegate.user.mySections count]; i++) {
		Section *old = [appDelegate.user.mySections objectAtIndex:i];
		for (int j=0; j<[newSections count]; j++) {
			Section *temp = [newSections objectAtIndex:j];
			if ([temp.sectionId isEqualToString:old.sectionId]) {
				old.oldFeedTitle = old.lastFeedTitle;
				old.lastFeedTitle = temp.lastFeedTitle;
				old.oldImageUrl = old.lastFeedImageUrl;
				old.lastFeedImageUrl = temp.lastFeedImageUrl;
				old.currentMaxId = temp.currentMaxId;
                old.childSections =temp.childSections;
				break;
			}
		}
	}
	[responseStr release];
	[response release];
	finishRequest = YES;
	[self gotoMainPage];
}

-(void) gotoMainPage{
	if (finishLayout && finishRequest) {//如果布局完成并且发出的远程请求完成
		
		
		appDelegate.rootViewController.sections = appDelegate.user.mySections;
		
		[self.activeView stopAnimating];
		[self.sectionContainer.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
		
		
		[UIView beginAnimations:@"animationID" context:nil];
		[UIView setAnimationDuration:1.0f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:appDelegate.window cache:YES];//oglFlip, fromLeft 
		
		[appDelegate.window addSubview:appDelegate.navigationController.view];
		
		[UIView commitAnimations];
		
	}
}

@end
